import request from '../../../../utils/axiosutils'
import Cookies from 'js-cookie'

const state = {
  uid: '',        // uid
  username: '',   // 用户名
  token: '',      // token
  role: ''        // 角色分组
}

const getters = {
  uid: state => state.uid,
  username: state => state.username,
  token: state => state.token,
  role: state => state.role
}

const mutations = {
  setUID: (state, data) => {
    if (data) {
      Cookies.set('uid', data)
    } else {
      Cookies.remove('uid')
    }
    state.uid = data
  },
  setName: (state, data) => {
    if (data) {
      Cookies.set('username', encodeURIComponent(data))
    } else {
      Cookies.remove('username')
    }
    state.username = data
  },
  setToken: (state, data) => {
    if (data) {
      Cookies.set('token', data)
    } else {
      Cookies.remove('token')
    }
    state.token = data
  },
  setRole: (state, data) => {
    if (data) {
      Cookies.set('role', encodeURIComponent(data))
    } else {
      Cookies.remove('role')
    }
    state.role = data
  }
}

const actions = {
  // 登录-用户名、密码查询是否有权限
  login ({ commit, rootState }, userInfo) {
    return new Promise((resolve, reject) => {
      const url = '/sysm/login'
      request.axiosCall(url, userInfo).then(res => {
        const data = res.data
        if (data.username) {
          commit('setUID', data.uid)
          commit('setName', data.username)
          commit('setToken', data.token)
          commit('setRole', data.role)
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 登出
  logout ({commit}) {
    return new Promise((resolve) => {
      commit('setUID', '')
      commit('setName', '')
      commit('setToken', '')
      commit('setRole', '')
      resolve()
    })
  },
  // 重新登录
  relogin ({commit}) {
    return new Promise((resolve) => {
      commit('setUID', Cookies.get('uid'))
      commit('setName', decodeURIComponent(Cookies.get('username')))
      commit('setToken', Cookies.get('token'))
      commit('setRole', decodeURIComponent(Cookies.get('role')))
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
